package models

type BCU struct {
	Model
	StationId int `json:"stationId" gorm:"station_id"`
	BSUId int `json:"bsuId" gorm:"column:bsu_id;default:null"`
	Status int `json:"status"`
}

func GetBCUsForUser(userId int) (bcus []BCU){
	var employments []Employment
	db.Table("bms_employment").Where("employer_id = ? or employee_id =?", userId, userId).Scan(&employments)
	for _, e := range employments {
		var tmp []BCU
		db.Where("station_id = ?", e.StationId).Find(&tmp)
		for _, t := range tmp {
			bcus = append(bcus, t)
		}
	}
	return
}

func GetBCUsByStationId(stationId int) (bcus []BCU) {
	db.Table("bms_bcu").Where("station_id = ?", stationId).Scan(&bcus)
	return
}

func GetBCUsByBSUId(bsuId int) (bcus []BCU) {
	db.Table("bms_bcu").Where("bsu_id = ?", bsuId).Scan(&bcus)
	return
}

func GetBCUSlave(id int) (bmus []BMU) {
	db.Select("bcu_id").Where("bcu_id = ?", id).Find(&bmus)
	return
}

func ExistBCUById(id int) bool {
	var bcu BCU
	db.Select("id").Where("id = ?", id).First(&bcu)
	return bcu.ID > 0
}

func AddBCU(id, stationId int) bool {
	db.Create(&BCU{
		Model: Model{ID: id},
		StationId: stationId,
	})
	return true
}

func AddBCUComplete(id, stationId, bsuId int) bool {
	db.Create(&BCU{
		Model: Model{ID: id},
		StationId: stationId,
		BSUId: bsuId,
	})
	return true
}

func DeleteBCU(id int) bool {
	db.Where("id = ?", id).Delete(&BCU{})
	return true
}

func CheckDeleteBCU(id int) bool {
	var bmu BMU
	db.Select("id").Where("bcu_id = ?", id).First(&bmu)
	if bmu.ID > 0{
		return false
	}
	return true
}

func UpdateBCU(id int, data interface{}) bool {
	db.Model(&BCU{}).Where("id = ?", id).Updates(data)
	return true
}
